<!--
 -----功能插槽使用-----
 添加/修改：add
    例：
 <template #add="{ formData，currentUpdateId }">  【formData：添加字段，currentUpdateId：是否是编辑】
        <el-form-item label="标题">
          <el-input v-model="formData.title" placeholder="请输入" />
        </el-form-item>
</template>
 -->
 <template>
  <div class="app-container">
    <!-- v-if="operationApi[3] != '-1' && searchDataList.length != 0 && operationApi[3] != '0'" -->
    <el-card
      v-loading="loading"
      shadow="never"
      class="search-wrapper"
      
    >
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item :label="item.title" v-for="(item, index) in searchDataList" :key="index">
          <el-input v-if="!item.type" v-model="searchData[item.name]" placeholder="请输入" />
          <el-date-picker
            v-else-if="item.type == 'time'"
            v-model="searchData[item.name]"
            type="datetimerange"
            format="YYYY/MM/DD"
            value-format="YYYYMMDD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-else-if="item.type == 'select'"
            v-model="searchData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.value || items.id"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'selectLable'"
            v-model="searchData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <slot name="addModel" :TableSelect_change="TableSelect_change" />
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button
            type="primary"
            :icon="CirclePlus"
            @click="handleAddbutton"
            v-if="operationApi[0] != '-1' && operationApi[0] != '0'"
            >新增</el-button
          >
          <el-button
            type="danger"
            :icon="Delete"
            @click="handleAllDelete"
            v-if="operationApi[4] && operationApi[4] != '-1' && operationApi[4] != '0'"
            >{{ plDelete || "批量删除" }}</el-button
          >
        </div>
        <div class="tabtitle">{{ title }}</div>
        <div>
          <el-tooltip content="下载" v-if="operationApi[5]">
            <el-button type="primary" @click="handleDowcvg" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="selection_change">
          <el-table-column
            type="selection"
            width="50"
            align="center"
            v-if="(operationApi[4] && operationApi[4] != '-1' && operationApi[4] != '0') || need_selection"
          />
          <template v-for="(item, index) in tableDataRule" :key="index">
            <el-table-column
              show-overflow-tooltip
              v-if="
                item.prop == 'update_time' ||
                item.prop == 'create_time' ||
                item.prop == 'last_active_time' ||
                item.prop == 'friend_give_time' ||
                item.prop == 'meetTime'
              "
              :prop="item.prop"
              :label="item.label"
              align="center"
            >
              <template #default="scope">
                {{ formatDateTime(scope.row[item.prop]) }}
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="item.prop == 'needButton'"
              fixed="right"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              align="center"
            >
              <template #default="scope">
                <slot :name="item.slot" :data="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="!item.slot"
              :prop="item.prop || '暂无内容'"
              :label="item.label"
              align="center"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row[item.prop] || "暂无内容" }}
              </template>
            </el-table-column>
            <el-table-column v-else :prop="item.prop" :label="item.label" align="center">
              <template #default="scope">
                <slot :name="item.slot" :data="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              v-if=" item.prop == 'operate'"
              fixed="right"
              label="操作"
              :width="caocuoWidth"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  text
                  bg
                  size="small"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button>
                <el-button
                  type="danger"
                  text
                  bg
                  size="small"
                  @click="handleDelete(scope.row)"
                  >{{ deleteText }}</el-button>
                <el-button
                  v-for="(item, index) in addButtonList"
                  :key="index"
                  text
                  bg
                  type="primary"
                  size="small"
                  @click="handleMoudleButton(scope.row, item.type)"
                  >{{ item.name }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <!-- <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper" v-if="needPagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      :width="formDataWidth"
    >
      <el-form
        :inline="formInline"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="labelWdth"
        label-position="right"
        :style="`align-items: center;`"
      >
        <slot name="add" v-if="dialogVisible" :formData="formData" :currentUpdateId="currentUpdateId" />
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateState">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, onMounted, computed } from "vue"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { usePermissionStoreHook } from "@/store/modules/permission"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { getToken } from "@/utils/cache/cookies"
import {
  createTableDataApi,
  deleteTableDataApi,
  updateTableDataApi,
  getTableDataApi,
  getTablePl
} from "@/api/table/index"
import { formatDateTime } from "@/utils/index"
// const StoreGhook = usePermissionStoreHook()
const RoleList:any = []//StoreGhook.RolesSelect //权限列表
onMounted(() => {
  init()
})
let formData = reactive<any>({})

const init = () => {
  // for (let index = 0; index < props!.operationApi!.length; index++) {
  //   if (!(RoleList.indexOf(props!.operationApi![index]) != -1)) {
  //     //没有找到
  //     props!.operationApi![index] = "-1"
  //   }
  // }
}
const handleMoudleButton = (row: any, type: string) => {
  emit("buttonMoudle", row, type)
}
const ButtonType = computed(() => {
  //拥有删除权限【过滤某些行的删除】
  return (item: any) => {
    //如果当前没有修改按钮权限
    // if (props.operationApi[2] == "0" || props.operationApi[2] == "-1") {
    //   return false
    // }
    //当前是否开启了每一行按钮状态
    if (props.needOperate) {
      if (props.needOperate.id.indexOf(item.id) != "-1") {
        //有禁止控制按钮
        return props.needOperate.update
      } else {
        return true
      }
    } else {
      //正常返回
      return true
    }
  }
})
const handleDowcvg = () => {
  // getTablecvg(props.svgOvj, props.operationApi[5]).then((res: any) => {
  //   const blob = new Blob([res], { type: "application/vnd.ms-excel" })
  //   //创建一个临时的Url只想blob对象
  //   const url = window.URL.createObjectURL(blob)
  //   const a = document.createElement("a")
  //   a.href = url
  //   a.download = `社区.csv`
  //   a.click()
  //   //释放
  //   window.URL.revokeObjectURL(url)
  // })
  const data: any = {}
  let str = ""
  //开启了选中当前行表格
  if (props.svgOvj) {
    if (TableSelect_change.value.length != 1) {
      ElMessage.warning("请选择一列")
      return
    }
    data[props.svgOvj as string] = TableSelect_change.value[0][props.svgOvj as string]
    for (const key in data) {
      if (data[key] != undefined) {
        str += `&${key}=${data[key]}`
      }
    }
  }
  window.open(`https://test.abox.v2.ssche.cn${props.operationApi[5]}?token=${getToken()}${str}`)
}
// const timeChange = (item: any) => {
//   searchData[item.name] = searchData[item.name][0] + " 至 " + searchData[item.name][1]
// }
const ButtonTypeDelete = computed(() => {
  return (item: any) => {
    //如果当前没有修改按钮权限
    // if (props.operationApi[1] == "0" || props.operationApi[1] == "-1") {
    //   return false
    // }
    //拥有删除权限【过滤某些行的删除】
    //当前是否开启了每一行按钮状态
    if (props.needOperate) {
      //如果开启
      if (props.needOperate.id.indexOf(item.id) != "-1") {
        //有禁止控制按钮
        return props.needOperate.delate
      } else {
        return true
      }
    } else {
      //正常返回
      return true
    }
  }
})
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const searchData = reactive<any>({}) //局部查询字段
const loading = ref<boolean>(false)
const tableData = ref<any>([]) //表格
const TableSelect_change = ref<any>([]) //table选择数组
const dialogVisible = ref<boolean>(false)
const currentUpdateId = ref<undefined | string>(undefined) //ID进行赋值按钮逻辑为编辑操作
const resetForm = () => {
  currentUpdateId.value = undefined
}
//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`是否确认该操作？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const obj: any = {}
    obj[props.DeleteId] = row[props?.DeleteIdValue ? props.DeleteIdValue : props.DeleteId]
    deleteTableDataApi(obj, props.operationApi[1]).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//自动执行编辑函数
const handleUpdateFun = (row: any) => {
  currentUpdateId.value = "1"
  formData = reactive({ ...row })
  dialogVisible.value = true
}
//修改
const handleUpdate = (row: any) => {
  if (props.needAUpdateFun) {
    emit("formDataUpdate", row)
    return
  }
  handleUpdateFun(row)
}

const props = withDefaults(
  defineProps<{
    //权限接口【根据权限接口判断是否拥有增删改查功能,：增、删、改、查、批量删、导入 按照顺序】
    operationApi: string[]
    //局部查询  普通字段查询 name:查询字段，title:标题
    //         列表查询字段 name:查询字段，title:标题，type:'select',list:[]
    //           时间段查询 name:查询字段，title:标题，type:'time'
    searchDataList?: {
      name: string
      title: string
      type?: string
      list?: { value: any; label: any; name?: string; id: string }[]
    }[]
    //table表格展示配置项   【slot可自定义，避免slot冲突参考功能插槽】
    // {
    //   prop: string
    //   label: string
    //   slot?: string
    //   width?: string
    // }[]
    tableDataRule?: any
    //删除当前表单的key
    DeleteId?: string
    //删除当前表单的Value[没有就默认以Key值显示Value]
    DeleteIdValue?: any
    //添加表单rule验证
    formRules?: { [name: string | number]: any }
    //是否需要手动添加【如果需要添加前的数据整理】
    needAddFun?: boolean //默认自动添加
    //是否需要手动修改【如果需要修改前的数据整理】
    needAUpdateFun?: boolean //默认自动修改
    //是否需要某些栏目禁止编辑删除按钮【默认不需要】匹配对应栏目ID
    // {
    //   id: ['1'],//根据当前列的ID进行操作按钮的隐藏和操作
    //   deleteButton: { update: true, delate: true }
    // }shequ_tab
    needOperate?: any
    //控制当前列表的删除功能控件和修改功能控件
    button_Type?: any
    //是否有默认查询必填字段 {[name]:value}
    mustSearchData?: any
    //是否需要分页器
    needPagination?: boolean
    //是否需要Table多项框
    need_selection?: boolean
    //table表格标题
    title?: string
    //是否开启选中当前行导出【string参数，一般为当前选中行的某些字段参数】
    svgOvj?: boolean | string
    //控制当前默认操作列表的长度
    caocuoWidth?: string | number
    //修改删除的基础上添加按钮配置项
    addButtonList?: { name: string; type: string }[] //name :按钮名称，type：'事件名称'
    //添加/编辑表单宽度
    formDataWidth?: string
    //同意表格标题的宽度
    labelWdth?: string
    //批量删除按钮标题
    plDelete?: string
    //删除按钮标题
    deleteText?: string
    //是否开启添加表单换行
    formInline?: boolean
  }>(),
  {
    formInline: false,
    deleteText: "删除",
    plDelete: "批量删除",
    searchDataList: () => [
      // { name: "name", title: "用户昵称" },
      // { name: "username", title: "用户账号" }
    ],
    formRules: () => {
      return {
        name: [{ required: true, trigger: "blur", message: "请输入标题" }]
      }
    },
    needAddFun: false,
    needAUpdateFun: false,
    button_Type: { delete: true, update: true },
    mustSearchData: null,
    needPagination: true,
    need_selection: false,
    DeleteId: "id",
    DeleteIdValue: false,
    //表格下载需要传递的参数
    svgOvj: false,
    caocuoWidth: "150",
    // addButtonList: [],
    formDataWidth: "30%",
    labelWdth: "100px"
  }
)
const selection_change = (row: any) => {
  TableSelect_change.value = row
}
const emit = defineEmits<{
  //新增用户
  (e: "formDataAdd", formData: any, flag: any): void
  //修改用户
  (e: "formDataUpdate", row: any): void
  (e: "buttonMoudle", row: any, type: string | number): void
}>()
//重置
const resetSearch = () => {
  for (const key in searchData) {
    searchData[key] = ""
  }
  searchObj.value = {}
  getTableData()
}
const searchObj = ref<any>({})
//局部查询接口
const handleSearch = () => {
  // paginationData.currentPage = 1vvd
  // if (paginationData.currentPage === 1) {
  searchObj.value = { ...searchData }
  props.searchDataList.forEach((item) => {
    if (item.type == "time") {
      //时间格式整理
      // obj[name]=
      if (searchObj.value[item.name]) {
        searchObj.value[item.name] = searchObj.value[item.name][0] + " 至 " + searchObj.value[item.name][1]
      }
    }
  })
  // console.log(searchObj, "12313")
  // return
  getTableData()
  // }
}
//表单查询
const getTableData = () => {
  for (const key in searchObj.value) {
    if (searchObj.value[key] == "") {
      delete searchObj.value[key]
    }
  }
  loading.value = true
  getTableDataApi(
    {
      page:  paginationData.page || "",
      pageSize:  paginationData.page_count || "",
      ...searchObj.value,
      ...(props.mustSearchData ? props.mustSearchData : {})
      // name: searchData.name || undefined,
      // path: searchData.path || undefined
    },
    props.operationApi[3]
  ).then((res: any) => {
    paginationData.total = res.data.total_count //总页数赋值
    tableData.value = res?.data?.data || res.data
    loading.value = false
  })
}
//批量删除
const handleAllDelete = () => {
  if (TableSelect_change.value.length == 0) {
    ElMessage.error("请至少选中一行!")
    return
  }
  ElMessageBox.confirm(`是否确认该操作？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const delArr: any = []
    TableSelect_change.value.forEach((item: any) => {
      delArr.push(item[props.DeleteId])
    })
    const obj: any = {}
    obj[props.DeleteId] = delArr
    getTablePl(obj, props.operationApi[4]).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//刷新表格
const handleRefresh = () => {
  getTableData()
}
const formRef = ref<FormInstance | null>(null)
const handleAddbutton = () => {
  //添加清空form表单
  formData = reactive({})
  dialogVisible.value = true
  formRef?.value?.resetFields()
}
const handleCreateState = () => {
  if (props.needAddFun) {
    //通过父组件进行数据整理
    emit("formDataAdd", formData, currentUpdateId.value)
  } else {
    handleCreate(formData)
  }
}
const handleCreate = (formData: any) => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // formData.is_menu = JSON.stringify(formData.is_menu)
      if (currentUpdateId.value === undefined) {
        createTableDataApi(formData, props.operationApi[0]).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getTableData()
        })
      } else {
        updateTableDataApi(
          {
            ...formData
          },
          props.operationApi[2]
        ).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
//方法/变量暴漏
defineExpose({ handleCreate, handleUpdateFun, getTableData, handleDowcvg })
/** 监听分页参数的变化 */
watch([() => paginationData.page, () => paginationData.page_count], getTableData, { immediate: true })
</script>
<style scoped lang="scss">
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.tabtitle {
  color: var(--el-text-color-primary);
  font-size: 16px;
  font-weight: 700;
}
</style>
